#!/bin/bash

cpDestOpts=--preserve=timestamps
Prefix=/my

if [[ "$PT_REPO_PATH" == "" ]];              then printf "PT_REPO_PATH not set!\n"     ; exit 1 ; fi
if [[ "$PT_BINDIR"    == "" ]];              then printf "PT_BINDIR not set!\n"        ; exit 1 ; fi
if [[ "$PT_BIT"       == "" ]];              then printf "PT_BIT not set!\n"           ; exit 1 ; fi
if [[ ($PT_BIT != 64) && ($PT_BIT != 32) ]]; then printf "Wrong PT_BIT (${PT_BIT})!\n" ; exit 1 ; fi

Result () {
  if [[ $1 == 0 ]]; then
    printf "\e[0;32mUpdating DLLs succeeded!\e[00m\n"
    exit 0
  else
    printf "\e[1;31mUpdating DLLs failed!\e[00m\n"
    exit 1
  fi
}

#=============================================================================

if [[ "$1" != "" ]]; then
  TheBindir="$1"
else
  if [ ! -d "$PT_REPO_PATH" ]; then
    echo "Path to repository \"$PT_REPO_PATH\" not found."
    exit 1
  fi
  TheBindir="$PT_REPO_PATH/$PT_BINDIR"
fi


echo "Updating all DLLs in $TheBindir ... "

if [ ! -d "$TheBindir" ]; then
  mkdir -p "$TheBindir"
else
  rm -f "$TheBindir/*.dll"
fi

if [[ "$PT_BIT" == "64" ]]; then
  cd /mingw/qt/bin && \
  cp QtCore4.dll \
     QtGui4.dll \
     QtNetwork4.dll \
     $TheBindir $cpDestOpts && \
  cd /mingw/bin && \
  cp libgcc_s_sjlj_64-1.dll \
     libgomp_64-1.dll \
     libstdc++_64-6.dll \
     pthreadGC2_64.dll \
     $TheBindir $cpDestOpts && \
  cd $Prefix/bin && \
  cp lensfun.dll \
     libexpat-1.dll \
     libfreetype-6.dll \
     libglib-2.0-0.dll \
     libintl-8.dll \
     zlib1.dll \
     $TheBindir $cpDestOpts

elif [[ "$PT_BIT" == "32" ]]; then
  cd /mingw/qt/bin && \
  cp QtCore4.dll \
     QtGui4.dll \
     QtNetwork4.dll \
     $TheBindir $cpDestOpts && \
  cd /mingw/bin && \
  cp libgcc_s_sjlj-1.dll \
     libgomp-1.dll \
     libstdc++-6.dll \
     pthreadGC2.dll \
     $TheBindir $cpDestOpts && \
  cd $Prefix/bin && \
  cp freetype6.dll \
     intl.dll \
     lensfun.dll \
     libexpat-1.dll \
     libglib-2.0-0.dll \
     zlib1.dll \
     $TheBindir $cpDestOpts
fi


if [[ $? == 0 ]]; then
  # There might be a special folder with non-debug libs complied with different optimizations
  # than the debug libs. In my setup that's true for the 32bit toolchain. The debugger started
  # from Qt Creator will pick up the libs from /my/bin any Photivo in a separate location
  # should get the non-debug libs.
  if [ -d $Prefix/bin/nodebug ]; then
    SrcDir=$Prefix/bin/nodebug/
  else
    SrcDir=$Prefix/bin/
  fi
  
  cp ${SrcDir}libexiv2.dll \
     ${SrcDir}libfftw3-3.dll \
     ${SrcDir}libGraphicsMagick-3.dll \
     ${SrcDir}libGraphicsMagick++-3.dll \
     ${SrcDir}libGraphicsMagickWand-2.dll \
     ${SrcDir}libiconv-2.dll \
     ${SrcDir}libjpeg-8.dll \
     ${SrcDir}liblcms2-2.dll \
     ${SrcDir}liblqr-1-0.dll \
     ${SrcDir}libpng15-15.dll \
     ${SrcDir}libtiff-3.dll \
     $TheBindir $cpDestOpts
fi

Result $?
